package com.binance.rabbitmq.config;

import com.binance.rabbitmq.exception.RabbitmqConfigurationException;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Singular;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * Created by robin.wu on 2018/11/29.
 */
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
@Log4j2
@ConfigurationProperties
public class BindingConfig extends AbstractConfig {

    /** 要绑定的交换器，注意，此处是exchange key,不是exchange name **/
    private String exchange;
    /** 要绑定的队列 **/
    private String queue;

    private String routingKey;

    @Singular
    private Map<String,Object> arguments;

    @Override
    public boolean validate() {
        boolean valid = true;
        if (StringUtils.isEmpty(getExchange())) {
            log.error("Invalid Exchange : Exchange must be provided for a binding");
            valid = false;
        }
        if (StringUtils.isEmpty(getQueue())) {
            log.error("Invalid Queue : Queue must be provided for a binding");
            valid = false;
        }
        if (valid) {
            log.info("Binding configuration validated successfully for Binding '{}'", this);
        }
        return valid;
    }

    public Binding bind(Exchange exchange, Queue queue) {
        if (ExchangeTypes.HEADERS.equals(exchange.getType()) && CollectionUtils.isEmpty(getArguments())) {
            throw new RabbitmqConfigurationException(String
                    .format("Invalid Arguments : Arguments must be provided for a header exchange for binding {%s}", this));
        } else if (StringUtils.isEmpty(getRoutingKey())) {
            throw new RabbitmqConfigurationException(String
                    .format("Invalid RoutingKey : RoutingKey must be provided for a non header exchange for binding {%s}", this));
        }
        return BindingBuilder.bind(queue).to(exchange).with(getRoutingKey()).and(getArguments());
    }
}
